package com.hz.framework.dao;

import java.io.Serializable;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.hz.framework.util.SqlParameter;
import com.hz.sessionFactory.HibernateSessionFactory;

/**
 * *****************************************************************************
 *               Copyright(c) 2010 by 哈尔滨华泽数码科技有限公司.
 *                       All rights reserved.
 *******************************************************************************
 *     File Name         :  com.hz.framework.dao.CommonIDU.java
 *     Description(说明)	: 公共增删改查方法类 包含增删该各一个方法，参数传入类对象即可。 
 *     						包含根据传入参数进行拼装HQL语句进行删除和更新的方法
 * 						包含一个根据所传参数进行拼装HQL的查询方法和一个传入HQL语句进行查询的方法
 * -----------------------------------------------------------------------------
 *     No.        Date              Revised by           Description
 *     @param <T>	  May 19, 2011           HTT              Created
 *****************************************************************************
 */
public class CommonIDU<T> extends CommonDBDao {

	private String strValue = "";
	private int iVerdict;
	private String strVName = "";
	private String[] strColumnV = null;
	private String hql = "";
	private Logger logger = Logger.getLogger(CommonIDU.class);
	private List lstsql = null;

	private static Session session = null;
	private static Transaction tx = null;
	private static boolean flag = false;

	public CommonIDU() {
	}
	/**
	 * @author 韩飞
	 * @time May 19, 2011	
	 * @param infor
	 * @return 
	 * 方法功能: 传对象插入方法
	 */
	public boolean insertinfor(T infor) {
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			session.save(infor);
			tx.commit();
			flag = true;
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			flag = false;
			e.printStackTrace();
		} finally {

				session.close();
		}
		return flag;
	}
	/**
	 * @author 韩飞
	 * @time May 19, 2011	
	 * @param list
	 * @return 
	 * 方法功能: 对list中的对象进行保存
	 */
	public static boolean saveList(List list) {
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			for (int i = 0; i < list.size(); i++) {
				session.save(list.get(i));
			}
			tx.commit();
			flag = true;
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			flag = false;
			e.printStackTrace();
		} finally {
			session.close();
		}
		return flag;
	}
	/**
	 * @author 韩飞
	 * @time May 19, 2011	
	 * @param object
	 * @return 
	 * 方法功能: 对list中的对象进行保存
	 */
	public boolean saveArray(T[] object) {
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			for (int i = 0; i < object.length; i++) {
				session.save(object[i]);
			}
			tx.commit();
			flag = true;
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			flag = false;
			e.printStackTrace();
		} finally {
			session.close();
		}
		return flag;
	}
	/**
	 * @author 韩飞
	 * @time May 19, 2011	
	 * @param list
	 * @return 
	 * 方法功能: 对list中的对象同时进行保存或更新
	 */
	public boolean saveOrupdate(List list) {
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			for (int i = 0; i < list.size(); i++) {
				session.saveOrUpdate(list.get(i));
			}
			tx.commit();
			flag = true;
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			flag = false;
			e.printStackTrace();
		} finally {
			session.close();
		}
		return flag;
	}
	/**
	 * @author 韩飞
	 * @time May 19, 2011	
	 * @param infor
	 * @return 
	 * 方法功能: 传对象插入方法返回主键,但是正常save后主键对象就直接有值了
	 */
	public String saveReturn(T infor) {
		String zj = "-1";
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			Serializable sz = session.save(infor);
			tx.commit();
			zj = sz.toString();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			zj = "-1";
			e.printStackTrace();
		} finally {
			session.close();
		}
		return zj;
	}
	/**
	 * @author 韩飞
	 * @time May 19, 2011	
	 * @param infor
	 * @return 
	 * 方法功能: 传对象更新方法
	 */
	public boolean updateinfor(T infor) {
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			session.update(infor);
			tx.commit();
			flag = true;
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
			flag = false;
		} finally {
			session.close();
		}
		return flag;
	}
	/**
	 * @author 韩飞
	 * @time May 19, 2011	
	 * @param hql
	 * @return 
	 * 方法功能: 传HQL处理 增 删 改 方法 String形式
	 */
	public boolean transactHql(String hql) {
		List<String> list = new ArrayList<String>();
		list.add(hql);
		return transactHqlplural(list);
	}
	/**
	 * @author 韩飞
	 * @time May 19, 2011	
	 * @param hql
	 * @return 
	 * 方法功能: 传HQL处理 增 删 改 方法 数组形式
	 */
	public boolean transactHqlplural(String[] hql) {
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			for (int i = 0; i < hql.length; i++)
				if(!"".equals(hql[i]))
					session.createQuery(hql[i]).executeUpdate();
			tx.commit();
			flag = true;
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
			flag = false;
		} finally {
			session.close();
		}
		return flag;
	}
	/**
	 * @author 韩飞
	 * @time May 19, 2011	
	 * @param hql
	 * @return 
	 * 方法功能:传HQL的处理 增 删 改 方法 list集合形式
	 */
	public boolean transactHqlplural(List hql) {
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			if(hql!=null&&!hql.isEmpty()){
				for (int i = 0; i < hql.size(); i++)
					if(!"".equals((String) hql.get(i)))
						session.createQuery((String) hql.get(i)).executeUpdate();
				tx.commit();
				flag = true;
			}else{
				flag = false;
			}
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			flag = false;
			e.printStackTrace();
		} finally {
			session.close();
		}
		return flag;
	}
	/**
	 * @author 韩飞
	 * @time May 19, 2011	
	 * @param sql
	 * @return 
	 * 方法功能: SQL 待测 处理 增 删 改 事件
	 */
	public boolean transactionSQL(String sql) {
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			Query query = session.createSQLQuery(sql);
			query.executeUpdate();
			tx.commit();
			flag = true;
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
			flag = false;
		} finally {
			session.close();
		}
		return flag;
	}
	/**
	 * @author 金雪冰 韩飞移植
	 * @time May 27, 2011	
	 * @param hql
	 * @param sqlParams
	 * @return 
	 * 方法功能:
	 */
	public int executeUpdate(String hql,SqlParameter sqlParams){
		int rs=0;
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			Query query = session.createQuery(hql);
			this.setParameters(query, sqlParams);
			rs = query.executeUpdate();
			tx.commit();
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}
			e.printStackTrace();
		} finally {
			session.close();
		}
		return rs;
	}
	/**
	 * @author 韩飞
	 * @time May 19, 2011	
	 * @param infor
	 * @return 
	 * 方法功能: 	传对象删除方法
	 */
	public boolean deleteinfor(T infor) {
		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			session.delete(infor);
			tx.commit();
			flag = true;
		} catch (Exception e) {
			if (tx != null) {
				tx.rollback();
			}

			e.printStackTrace();
			flag = false;
		} finally {
			session.close();
		}
		return flag;
	}
	/**
	 * @author 韩飞
	 * @time May 19, 2011	
	 * @param table
	 * @param field
	 * @param column
	 * @param request
	 * @return 
	 * 方法功能: 修改方法,参数（表名,更新字段名数组,where条件名数组,request）,页面的字段名必须跟数据库中字段名一样
	 */
	public boolean updatesTable(String table, String[] field, String[] column, HttpServletRequest request) {
		iVerdict = column.length;
		strVName = "";
		strColumnV = request.getParameterValues(column[0]);
		lstsql = new ArrayList();
		if (column != null && !"".equals(table) && field != null
				&& strColumnV != null) {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			/* 执行DELETESQL */
			for (int i = 0; i < strColumnV.length; i++) {// 确定更新条数
				hql = "update " + table + " set ";
				for (int j = 0; j < field.length; j++) {

					if (request.getParameterValues(field[j]) != null) {
						if (request.getParameterValues(field[j]).length == strColumnV.length) {
							strValue = request.getParameterValues(field[j])[i];
							strValue = strValue == null ? "" : strValue;
							if (j != field.length - 1) {
								hql += field[j] + "='" + strValue + "',";
							} else {
								hql += field[j] + "='" + strValue + "' ";
							}
						} else {
							strValue = request.getParameter(field[j]);
							strValue = strValue == null ? "" : strValue;
							if (j != field.length - 1) {
								hql += field[j] + "='" + strValue + "',";
							} else {
								hql += field[j] + "='" + strValue + "' ";
							}
						}
					}
				}
				hql += " where ";
				for (int j = 0; j < iVerdict; j++) {
					strValue = request.getParameterValues(column[j])[i];
					if (!"".equals(strValue) && strValue != null) {
						if (j != iVerdict - 1) {
							hql += column[j] + "='" + strValue + "' and ";
						} else {
							hql += column[j] + "='" + strValue + "' ";
						}
					}
				}
				lstsql.add(hql);
			}
			try {
				for (int s = 0; s < lstsql.size(); s++) {
					Query query = session.createQuery(lstsql.get(s).toString());
					query.executeUpdate();
					System.out.println(query.toString());
				}
				tx.commit();
				logger.info("update true!");
				return true;
			} catch (Exception e) {
				if (tx != null) {
					tx.rollback();
				}
				e.printStackTrace();
				return false;
			} finally {
				session.close();
			}
		} else {
			logger.info("update false!not table or field value");
			return false;
		}
	}
	/**
	 * @author 韩飞
	 * @time May 19, 2011	
	 * @param table
	 * @param column
	 * @param request
	 * @return 
	 * 方法功能: 删除方法,参数（表名,where条件名数组,request）,页面的字段名必须跟数据库中字段名一样
	 */
	public boolean DeleteCheck(String table, String[] column,HttpServletRequest request) {
		iVerdict = column.length;
		strVName = column[0];
		strColumnV = request.getParameterValues(strVName);
		lstsql = new ArrayList();
		if (column != null && !"".equals(table) && strColumnV != null) {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			/* 执行DELETESQL */
			for (int i = 0; i < strColumnV.length; i++) {
				hql = "delete from " + table + " where ";
				for (int j = 0; j < iVerdict; j++) {
					strValue = request.getParameterValues(column[j])[i];
					if (!"".equals(strValue) && strValue != null) {
						if (j != iVerdict - 1)
							hql += column[j] + "='" + strValue + "' and ";
						else
							hql += column[j] + "='" + strValue + "' ";
					}
				}
				lstsql.add(hql);
			}
			try {
				for (int s = 0; s < lstsql.size(); s++) {
					Query query = session.createQuery(lstsql.get(s).toString());
					query.executeUpdate();
					System.out.println(query.toString());
				}
				tx.commit();
				logger.info("delete true!");
				return true;
			} catch (Exception e) {
				if (tx != null) {
					tx.rollback();
				}
				e.printStackTrace();
				return false;
			} finally {
				session.close();
			}

		} else {
			logger.info("delete false!not table or field value");
			return false;
		}
	}

	/**
	 * @author 韩飞
	 * @time May 19, 2011	
	 * @param table
	 * @param id
	 * @param request
	 * @return 
	 * 方法功能: 单条件删除方法,参数（表名,where条件id,request）,页面的字段名必须跟数据库中字段名一样
	 */
	public boolean DeleteOne(String table, String id, HttpServletRequest request) {
		strColumnV = request.getParameterValues(id);
		if (!"".equals(id) && !"".equals(table) && strColumnV != null) {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			/* 执行DELETESQL */
			hql = "delete from " + table + " where " + id + " in (";
			for (int i = 0; i < strColumnV.length; i++) {
				strValue = request.getParameterValues(id)[i];
				if (!"".equals(strValue) && strValue != null) {
					if (i != strColumnV.length - 1)
						hql += "'" + strValue + "',";
					else
						hql += "'" + strValue + "')";
				}
			}
			try {
				Query query = session.createQuery(hql);
				query.executeUpdate();
				tx.commit();
				logger.info("delete true!");
				return true;
			} catch (Exception e) {
				if (tx != null) {
					tx.rollback();
				}
				e.printStackTrace();
				return false;
			} finally {
				session.close();
			}
		} else {
			logger.info("delete false!not table or field value");
			return false;
		}
	}
	/**
	 * @author 韩飞
	 * @time May 19, 2011	
	 * @param table
	 * @param where
	 * @param value
	 * @return 
	 * 方法功能: 执行一个集合的删除功能 参数: 表名 , where条件(单一), 对应的值的集合
	 */
	public boolean DeleteHql(String table, String where, String value) {
		if (!"".equals(table)) {
			hql = "delete from " + table ;
			if(!"".equals(where)){
				hql += " where " + where + " in (" + value + ")";
			}
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			/* 执行DELETESQL */
			try {
				session.createQuery(hql).executeUpdate();
				tx.commit();
				logger.info("delete true!");
				return true;
			} catch (Exception e) {
				if (tx != null) {
					tx.rollback();
				}
				return false;
			} finally {
				session.close();
			}
		} else {
			logger.info("delete false!not table or field value");
			return false;
		}
	}
	
	/***************************************************************************
	 * 添加参数。
	 * 
	 * @param sqlParams
	 */
	private void setParameters(Query q, SqlParameter sqlParams) {
		if (sqlParams != null && sqlParams.size() > 0) {
			for (int i = 0; i < sqlParams.size(); i++) {
				q.setParameter(i, sqlParams.get(i));
				// TODO Auto-generated catch block
			}
		}
	}
	public static void main(String[] args) {
	
	}
	

}
